﻿using System;
using System.Collections.Generic;
using System.Linq;
using NHibernate;
using NHibernate.Linq;
using NHibernate.Criterion;
using Hasiu.Entity;

namespace Hasiu.Service
{
    public class MessagesService
    {
        public static readonly MessagesService _ = new MessagesService();

        private ISession Session { get; set; }

        public MessagesService()
        {
            Session = NHibernateHelper.GetCurrentSession();
        }

        public void Save(Messages messages)
        {
            Session.Clear();
            Session.Save(messages);
            Session.Flush();
        }

        public void Update(Messages messages)
        {
            Session.Clear();
            Session.Update(messages);
            Session.Flush();
        }

        public void Delete(params string[] id)
        {
            Session.Clear();
            var query = Session.Query<Messages>().Where(o => id.Contains(o.Id));
            foreach (var v in query)
            {
                Session.Delete(v);
            }
            Session.Flush();
        }

        public Messages Get(string id)
        {
            return Session.Get<Messages>(id);
        }

        public IList<Messages> GetList(
            int pageIndex,
            int pageSize,
            out int dataCount,
            DateTime? startTime,
            DateTime? endTime)
        {
            var queryCount = Session.CreateCriteria(typeof(Messages));
            var queryList = Session.CreateCriteria(typeof(Messages));
            if (startTime != null)
            {
                queryCount.Add(Restrictions.Gt("AddTime", startTime));
                queryList.Add(Restrictions.Gt("AddTime", startTime));
            }
            if (endTime != null)
            {
                queryCount.Add(Restrictions.Lt("AddTime", endTime));
                queryList.Add(Restrictions.Lt("AddTime", endTime));
            }
            dataCount = Convert.ToInt32(queryCount.SetProjection(Projections.Count("Id")).UniqueResult());
            return queryList.AddOrder(new Order("AddTime", false))
                .SetFirstResult(pageIndex * pageSize)
                .SetMaxResults(pageSize)
                .List<Messages>();
        }
    }
}
